import React from "react";
import {Navigate, useLoaderData, useLocation, useNavigate} from "react-router-dom";
import type {MetaProps} from "@/router/interface";
import {getCookieToken} from "@/utils/auth.ts";
import {useDispatch} from "@/store";

enum ENUM {
    LOGIN = '/login'
}

const RouterGuard = ({children}: { children: React.ReactNode }): React.ReactNode => {
    const loader = useLoaderData() as MetaProps;
    const {pathname} = useLocation()
    const token = getCookieToken()
    window.$navigate = useNavigate();
    window.$dispatch = useDispatch();

    if (loader) document.title = loader?.title ? `${loader.title} - React Admin` : 'React Admin';

    if (!token && pathname == ENUM.LOGIN) {
        //没token访问的是登录页
        return children
    } else if (!token && pathname !== ENUM.LOGIN) {
        //没token访问的不是登录页
        return <Navigate to={`${ENUM.LOGIN}?redirect=${pathname}`} replace/>
    } else if (token && pathname == ENUM.LOGIN) {
        //有token访问的是登录页
        return <Navigate to='/home'/>
    } else if (token && pathname !== ENUM.LOGIN) {
        //有token访问非登录页面
        return children
    }
}

export default RouterGuard
